<?php

namespace app\models;

use app\config\Constants;
use Yii;
use yii\base\NotSupportedException;
use yii\db\AfterSaveEvent;
use yii\web\IdentityInterface;
use yii\web\UnauthorizedHttpException;

/**
 * This is the model class for table "merchant".
 *
 * @property int $merchant_id 自增ID
 * @property string $merchant_name 店铺名称
 * @property string $merchant_desc 店铺描述
 * @property string $mini_store_img 小程序店铺入口地址
 * @property string $thumbnail 店铺门店照
 * @property string $cat_name 分类名称
 * @property int $sort 排序
 * @property int $status 店铺状态:1禁用,2正常
 * @property int $customer_type 客户类型:1两者,2商户,3用户
 * @property string $lng_lat 经度和纬度
 * @property string $announce 公告
 * @property int $is_show 是否显示：1否,2是
 * @property int|null $auto_accept 自动接单:1否,2是
 * @property string|array $business_time 营业时间
 * @property int $delivery_type 配送方式:1商家配送,2平台配送
 * @property string $delivery_rule 配送规则
 * @property string $add_time 添加时间
 *
 * @property MerchantCredential[] $merchantCredentials
 * @property MerchantInfo $merchantInfo
 */
class Merchant extends \yii\db\ActiveRecord implements IdentityInterface
{
    public function init()
    {
        parent::init();
        $this->on(self::EVENT_AFTER_UPDATE,[$this,'afterUpdate']);
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'merchant';
    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        if($token->getClaim("credential") != Constants::MERCHANT){
            throw new UnauthorizedHttpException(Yii::t("app","令牌凭证错误"));
        }
        return self::findIdentity($token->getClaim("uid"));
    }

    public function getId()
    {
        return $this->merchant_id;
    }

    //同步更新订单的商户名称
    public function afterUpdate(AfterSaveEvent $event){
        if(isset($event->changedAttributes['merchant_name'])){
            GoodsOrder::updateAll(
                ['merchant_name'=>$event->sender->merchant_name],
                ['merchant_id'=>$event->sender->merchant_id]
            );
        }
    }

    public function getAuthKey()
    {
        throw new NotSupportedException("getAuthKey不支持");
    }

    public function validateAuthKey($authKey)
    {
        throw new NotSupportedException("getAuthKey不支持");
    }

    /**
     * Gets query for [[MerchantCredentials]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getMerchantCredentials()
    {
        return $this->hasMany(MerchantCredential::className(), ['merchant_id' => 'merchant_id']);
    }

    /**
     * Gets query for [[MerchantInfo]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getMerchantInfo()
    {
        return $this->hasOne(MerchantInfo::className(), ['merchant_id' => 'merchant_id']);
    }
}
